package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    private final SysDeptMapper deptMapper;

    public SysDeptServiceImpl(SysDeptMapper deptMapper) {
        this.deptMapper = deptMapper;
    }

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "sd")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "sd")
    public List<Ztree> selectDeptTree(SysDept dept) {
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        return initZtree(deptList);
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "sd")
    public List<Ztree> selectDeptTreeExcludeChild(SysDept dept) {
        Long deptId = dept.getDeptId();
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        deptList.removeIf(d -> d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return initZtree(deptList);
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = selectDeptList(new SysDept());
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDept dept : deptList) {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setType(dept.getType());
                ztree.setDeptLevel(dept.getLevel());
                ztree.setTitle(dept.getDeptName());
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        SysDept dept = new SysDept();
        dept.setParentId(parentId);
        return deptMapper.selectDeptCount(dept);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public List<SysDept> selectChildrenDeptFilterByTypes(SysDept sysDept, String...types) {
        SysDept childDept = new SysDept();
        childDept.setParentId(sysDept.getDeptId());
        childDept.setParams(sysDept.getParams());
        childDept.setType(sysDept.getType());
        return deptMapper.selectChildrenDeptFilterByTypes(childDept, types);
    }

    @Override
    @DataScope(deptAlias = "sd", userAlias = "su")
    public List<SysDept> selectChildrenDeptByUser(SysUser user, Byte type) {
        return deptMapper.selectChildrenDeptByUser(user, type);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId() != deptId) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    @Override
    public void importDept() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("E:\\华为云盘\\telecom\\Programs\\一村一册\\20年网格构架12.16.csv")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] dept = line.split(",");
                Map<String, String> deptMap = new HashMap<>(8);
                deptMap.put("id3", dept[1]);
                deptMap.put("name3", dept[2]);
                deptMap.put("id4", dept[3]);
                deptMap.put("name4", dept[4]);
                deptMap.put("id5", dept[5]);
                deptMap.put("name5", dept[6]);
                deptMap.put("id6", dept[7]);
                deptMap.put("name6", dept[8]);
                insertSixUnitDept(deptMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void insertSixUnitDept(Map<String, String> deptMap) {
        //三级单元
        SysDept sysDept3 = new SysDept();
        sysDept3.setParentId(100L);
        sysDept3.setAncestors("100");
        sysDept3.setDeptId(Long.valueOf(deptMap.get("id3")));
        sysDept3.setDeptName(deptMap.get("name3"));
        duplicatedCode(sysDept3);


        //四级单元
        SysDept sysDept4 = new SysDept();
        sysDept4.setParentId(sysDept3.getDeptId());
        sysDept4.setAncestors(deptMap.get("id3"));
        sysDept4.setDeptId(Long.valueOf(deptMap.get("id4")));
        sysDept4.setDeptName(deptMap.get("name4"));
        duplicatedCode(sysDept4);

        //五级单元
        SysDept sysDept5 = new SysDept();
        sysDept5.setParentId(sysDept4.getDeptId());
        sysDept5.setAncestors(deptMap.get("id3") + "," + deptMap.get("id4"));
        sysDept5.setDeptId(Long.valueOf(deptMap.get("id5")));
        String deptName5 = deptMap.get("name5");
        sysDept5.setDeptName(deptName5);
        duplicatedCode(sysDept5);

        //六级单元
        SysDept sysDept6 = new SysDept();
        sysDept6.setParentId(sysDept5.getDeptId());
        sysDept6.setAncestors(deptMap.get("id3") + "," + deptMap.get("id4") + "," + deptMap.get("id5"));
        sysDept6.setDeptId(Long.valueOf(deptMap.get("id6")));
        String deptName6 = deptMap.get("name6");
        sysDept6.setDeptName(deptName6);
        duplicatedCode(sysDept6);
    }

    private void duplicatedCode(SysDept dept) {
        dept.setOrderNum("0");
        dept.setStatus("0");
        dept.setCreateBy("admin");
        dept.setCreateTime(new Date());
        if (Objects.isNull(deptMapper.selectDeptById(dept.getDeptId()))) {
            deptMapper.insertDept(dept);
        }
    }
}
